package com.msblearn.C_005;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * T10_ReentrantLock:可重入锁
 * 注意：Reentrant必须解锁。并要卸载finally里面
 */
public class T01_ReentrantLock2 {
    Lock lock = new ReentrantLock();

    private void m1() {
        try {
            lock.lock();
            for (int i = 0; i < 10; i++) {

                TimeUnit.SECONDS.sleep(1);

                System.out.println(i);
                if (i == 2) {
                    m2();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //必须写在finally
            lock.unlock();
        }

    }

    private void m2() {
        try {
            lock.lock();
            System.out.println("m2.....");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T01_ReentrantLock2 reentrantLock1 = new T01_ReentrantLock2();
        new Thread(reentrantLock1::m1).start();
        TimeUnit.SECONDS.sleep(1);
        //会等待m1完成才会执行。等待锁。
        new Thread(reentrantLock1::m2).start();

    }
}
